<template>
  <!-- 添加项目资源检索的弹窗 -->
  <el-card class="project-resources-card" style="max-width: 800px; margin: 130px auto;">
    <h3 style="text-align: center; width: 100%; margin: 10px 0 15px 15px">
      自动检索村级工程项目发包公告、中标公示相关资料
    </h3>
    <el-form
        ref="formRef"
        :model="fetchForm"
        :rules="rules"
        label-width="80px"
        :disabled="isFetching"
    >
      <el-form-item label="选择乡镇" prop="department">
        <el-select
            v-model="selectedDepartment"
            filterable
            remote
            :remote-method="searchDepartments"
            :loading="departmentsLoading"
            placeholder="请输入乡镇名称或从下拉列表中选取"
            @change="fillUrl"
            style="width: 100%"
        >
          <el-option
              v-for="dept in filteredDepartments"
              :key="dept._id"
              :label="dept.name"
              :value="dept.name"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="项目网址" prop="url">
        <el-input
            v-model="fetchForm.url"
            placeholder="请选择乡镇以自动填充网址"
            readonly
        />
      </el-form-item>

      <template v-if="searchType === 'page'">
        <el-form-item label="检索范围" required>
          <el-col :span="11">
            <el-form-item prop="startPage">
              <el-input-number
                  v-model="fetchForm.startPage"
                  :min="1"
                  :max="67"
                  placeholder="开始页（每页15条记录）"
                  style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="2" class="text-center">-</el-col>
          <el-col :span="11">
            <el-form-item prop="endPage">
              <el-input-number
                  v-model="fetchForm.endPage"
                  :min="1"
                  :max="67"
                  placeholder="结束页（最大67页）"
                  style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-form-item>
      </template>

      <template v-if="searchType === 'date'">
        <el-form-item label="快速选取" prop="timeRange">
          <el-radio-group v-model="selectedTimeRange" @change="handleTimeRangeChange">
            <el-radio :label="1">1个月</el-radio>
            <el-radio :label="2">2个月</el-radio>
            <el-radio :label="3">3个月</el-radio>
            <el-radio :label="6">6个月</el-radio>
            <el-radio :label="12">1年</el-radio>
            <span style="margin-left: 20px"></span>
          </el-radio-group>
          <el-checkbox v-model="selectAllTime" @change="handleSelectAllTimeChange">自定义</el-checkbox>
        </el-form-item>

        <el-form-item label="时间范围" required>
          <el-col :span="11">
            <el-form-item prop="startDate">
              <el-date-picker
                  v-model="fetchForm.startDate"
                  type="date"
                  placeholder="开始日期"
                  style="width: 100%"
                  :disabled-date="disabledDate"
              />
            </el-form-item>
          </el-col>
          <el-col :span="2" class="text-center">-</el-col>
          <el-col :span="11">
            <el-form-item prop="endDate">
              <el-date-picker
                  v-model="fetchForm.endDate"
                  type="date"
                  placeholder="结束日期"
                  style="width: 100%"
                  :disabled-date="disabledDate"
              />
            </el-form-item>
          </el-col>
        </el-form-item>
      </template>

      <el-row :gutter="20" style="margin-bottom: 10px; display: flex; align-items: center;">
        <el-col :span="12">
          <el-form-item label="检索方式" style="display: flex; align-items: center; height: 100%;">
            <el-radio-group v-model="searchType" style="display: flex; align-items: center; height: 100%;">
              <el-radio value="date" style="margin-right: 8px; display: flex; align-items: center;">按时间检索
              </el-radio>
              <el-radio value="page" style="display: flex; align-items: center;">按页码检索</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>

        <el-col :span="12" style="display: flex; align-items: center;">
          <el-form-item style="display: flex; align-items: center; width: 100%">
            <div style="font-size: 14px; color: #d2d2d2;">
              默认每分钟检索10页，请尽量分段检索
            </div>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20" style="margin-bottom: 10px; display: flex; align-items: center;">
        <el-col :span="5">
          <el-checkbox v-model="keepCounty"
                       style="display: flex; align-items: center; height: 100%; padding-left: 8px">
            项目前缀 新化县
          </el-checkbox>
        </el-col>
        <el-col :span="12" style="display: flex; align-items: center;">
          <label style="white-space: nowrap; margin-right: 10px;">后缀:</label>
          <el-checkbox-group
              v-model="selectedSuffixes"
              @change="handleSuffixChange" style="display: flex; align-items: center;"
          >
            <el-checkbox value="工程" style="margin-right: 12px;">工程</el-checkbox>
            <el-checkbox value="项目" style="margin-right: 12px;">项目</el-checkbox>
            <el-checkbox value="工程项目">工程项目</el-checkbox>
          </el-checkbox-group>
        </el-col>
        <el-col :span="7" style="display: flex; align-items: center;">
          <label style="white-space: nowrap; margin: 0 10px 0 18px;">小数点位数:</label>
          <el-radio-group v-model="decimalPlaces" style="display: flex; align-items: center;">
            <el-radio value="2" style="margin-right: 12px;">2位</el-radio>
            <el-radio value="4">4位</el-radio>
          </el-radio-group>
        </el-col>
      </el-row>
    </el-form>

    <div style="text-align: center; font-size: 14px; color: #d2d2d2; margin-bottom: 30px;">
      设置工程项目后缀为统一格式，如：工程、项目或工程项目，能提高发包与中标的合并率
    </div>

    <template #footer>
      <div class="dialog-footer">
        <!-- 性能模式控制组件靠左 -->
        <div class="performance-control">
          <span class="performance-label">检索模式：</span>
          <el-segmented
              v-model="performanceMode"
              :options="performanceOptions"
              @change="handlePerformanceModeChange"
              class="performance-segmented"
          />
        </div>

        <!-- 操作按钮靠右 -->
        <div class="button-group">
          <el-button @click="closeWindow" :disabled="isFetching">关闭</el-button>
          <div style="position: relative; width: 80px; height: 32px; margin-left: 12px;">
            <el-button
                type="primary"
                :disabled="!canSubmit"
                @click="submitFetch"
                style="width: 100%; height: 100%;"
            >
              {{ isFetching ? progressText : '开始检索' }}
            </el-button>
          </div>
        </div>
      </div>
    </template>
  </el-card>

  <!-- 检索结果展示容器 -->
  <div v-show="showResultsDialog" class="project-results-container">
    <div class="results-content">
      <div class="results-header">
        <h3 style="text-align: center; width: 100%; margin: 0 0 15px 0">
          从新化县人民政府网站，检索到的村级工程项目发包公告、中标公示资料
        </h3>
      </div>

      <el-table
          :data="paginatedData"
          border
          stripe
          height="100%"
          highlight-current-row
          style="width: 100%; flex: 1;"
          :header-cell-style="headerCellStyle"
          :row-style="rowStyle"
          :cell-style="cellStyle"
      >
        <el-table-column prop="projectName" label="项目名称" width="224" header-align="center"/>
        <el-table-column prop="constructionAddress" label="项目地址" width="154" header-align="center"/>
        <el-table-column prop="constructionContent" label="建设内容" min-width="300" header-align="center"/>
        <el-table-column prop="biddingTime" label="发包日期" width="96" header-align="center" align="center"/>
        <el-table-column prop="totalPrice" label="发包金额" width="86" header-align="center" align="right"/>
        <el-table-column prop="winningTime" label="中标日期" width="96" header-align="center" align="center"/>
        <el-table-column prop="bidAmount" label="中标金额" width="86" header-align="center" align="right"/>
        <el-table-column prop="winningBidder" label="中标人" width="154" header-align="center"/>
        <el-table-column label="操作" width="80" fixed="right" header-align="center" align="left">
          <template #default="scope">
            <div style="display: flex; flex-direction: column; align-items: flex-start; margin: 0; padding: 0;">
              <el-button
                  size="small"
                  type="primary"
                  @click="openSourceUrl(scope.row)"
                  title="查看工程项目资料来源网站"
                  style="margin: 0 0 4px 0; width: 60px;"
              >
                数据源
              </el-button>
              <el-button
                  size="small"
                  @click="exportTo(scope.row)"
                  title="自动填写小微权力表格数据"
                  style="margin: 0; width: 60px;"
              >
                导出到
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <div class="results-footer">
        <div style="display: flex; justify-content: space-between; align-items: center; width: 100%;">
          <el-col :span="6" style="display: flex; align-items: center;">
            <el-checkbox
                v-model="sortByName"
                :disabled="isFetching"
                style="display: flex; align-items: center; justify-content: flex-start; padding-left: 8px; margin-right: 20px;"
                @change="handleSortByNameChange"
            >
              按项目名称排序
            </el-checkbox>

            <el-checkbox
                v-model="mergeProjects"
                :disabled="isFetching || !sortByName"
                style="display: flex; align-items: center; justify-content: flex-start; margin-right: 20px;"
                @change="handleMergeProjectsChange"
            >
              合并发包、中标项目
            </el-checkbox>

            <el-checkbox
                v-model="includeNonProjects"
                :disabled="isFetching"
                style="display: flex; align-items: center; justify-content: flex-start;"
                @change="handleIncludeNonProjectsChange"
            >
              包含非工程项目
            </el-checkbox>
          </el-col>

          <el-row style="width: 100%; display: flex; justify-content: space-between; align-items: center;">
            <el-col :span="12" style="display: flex; justify-content: center;">
              <el-pagination
                  :pager-count="7"
                  @size-change="handleSizeChange"
                  @current-change="handleCurrentChange"
                  :current-page="currentPage"
                  :page-size="pageSize"
                  layout="total, sizes, first, pager, last, jumper"
                  :total="total"
                  style="margin: 0;"
                  :background="true"
                  hide-on-single-page
              />
            </el-col>

            <el-col :span="6" style="display: flex; justify-content: flex-end; align-items: center;">
              <div style="display: flex; align-items: center; margin-right: 12px;">
                <label style="margin-right: 8px; font-size: 14px; width: 40px">筛选:</label>
                <el-input
                    v-model="villageFilterInput"
                    placeholder="输入村名"
                    clearable style="width: 100px; margin-right: 30px"
                    @input="handleVillageFilterChange"
                />
              </div>
              <el-button @click="handleReturn" :disabled="isFetching">返回</el-button>
              <el-button @click="handleImportExcel" :disabled="isFetching" style="margin-left: 12px;">
                导入Excel
              </el-button>
              <el-button type="primary" @click="exportResults" :disabled="isFetching" style="margin-left: 12px;">
                导出Excel
              </el-button>
            </el-col>
          </el-row>
        </div>
      </div>

      <!--  进度条  -->
      <div v-if="isFetching" style="position: absolute; bottom: 0; left: 0; right: 0; margin: 0; padding: 0;">
        <el-progress
            :percentage="progress"
            :stroke-width="17"
            text-inside
            striped
            striped-flow
            color="#909399"
        >
          <div
              style="position: absolute; top: 0; left: 0; right: 0; bottom: 0; display: flex; align-items: center; justify-content: center;">
            <span style="color: #fff; font-size: 11px;">{{ progressText || `${progress}%` }}</span>
          </div>
        </el-progress>
      </div>
    </div>
  </div>

  <div
      v-if="showAutoFillDialog"
      style="position: absolute; top: 0; left: 0; width: 100%; height: 100%; padding-top: 20px; background-color: rgba(0, 0, 0, 0.3); z-index: 500;"
  >
    <AutoFillModule
        :rowData="currentRowData"
        @close="showAutoFillDialog = false"
    />
  </div>
</template>

<script setup>
import {useRouter} from 'vue-router';
import {ref, onMounted, watch, computed} from 'vue'
import axios from 'axios'
import {ElMessage} from "element-plus"
import * as XLSX from 'xlsx'
import {mergeProjectRecords} from '@/utils/projectMerger.js'
import AutoFillModule from "@/views/AutoFillModule.vue";
import {formatDate} from "@/utils/commonUtils";

const router = useRouter();

// 定义组件的属性
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  baseUrl: {
    type: String,
    default: ''
  }
})

// 定义组件的事件
const emit = defineEmits(['update:visible', 'close'])

// 表单引用
const formRef = ref()

// 表单验证规则
const rules = {
  department: [{required: false, message: '请选择乡镇', trigger: 'change'}],
  url: [{required: false, message: '请选择乡镇以自动填充网址', trigger: 'change'}],
  startPage: [{required: false, message: '请输入开始页', trigger: 'blur'}],
  endPage: [{required: false, message: '请输入结束页', trigger: 'blur'}]
}

// 表单数据
const fetchForm = ref({
  url: '',
  startPage: null,
  endPage: null,
  startDate: '',
  endDate: ''
});

// 状态管理
const isFetching = ref(false)
const keepCounty = ref(false)
const mergeProjects = ref(false)
const includeNonProjects = ref(true)
const selectedSuffixes = ref(['工程项目'])
const decimalPlaces = ref('2')
const showResultsDialog = ref(false)
const fetchedData = ref([])
const progress = ref(0)
const progressInterval = ref(null)
const progressInfo = ref({processedItems: 0, totalItems: 0})
const sortByName = ref(false)
const progressText = ref('')
const searchType = ref('date');

// 村筛选器相关状态
const villageFilter = ref('')
const villageFilterInput = ref('')

// 自动填充相关
const showAutoFillDialog = ref(false)
const currentRowData = ref(null)

// 定义数据源
const baseUrl = process.env.VUE_APP_API_BASE_URL;

// 时间范围相关
const selectedTimeRange = ref(1);
const selectAllTime = ref(false);

// 分页相关状态
const currentPage = ref(1)
const pageSize = ref(10)

// 乡镇选择相关
const departments = ref([])
const filteredDepartments = ref([])
const selectedDepartment = ref('')
const departmentsLoading = ref(false)


// 性能模式控制 - 保持原有结构，但调整值的设置方式
const performanceMode = ref('balance') // 默认平衡模式
const performanceOptions = [
  { label: '速度', value: 'speed' },
  { label: '平衡', value: 'balance' },
  { label: '性能', value: 'performance' }
]

// 延时参数映射
const delaySettings = {
  speed: { pageDelay: 50, detailDelay: 100 },
  balance: { pageDelay: 100, detailDelay: 300 },
  performance: { pageDelay: 150, detailDelay: 500 }
}

// 获取当前延时设置
const getCurrentDelaySettings = () => {
  return delaySettings[performanceMode.value] || delaySettings.balance
}

// 处理性能模式变化
const handlePerformanceModeChange = (value) => {
  console.log('性能模式已更改为:', value)
}


// 计算属性
const total = computed(() => villageFilteredData.value.length)

const paginatedData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return villageFilteredData.value.slice(start, end)
})

const processedData = computed(() => {
  let data = [...filteredData.value]

  // 如果需要按项目名称排序
  if (sortByName.value) {
    data.sort((a, b) => a.projectName.localeCompare(b.projectName));
  }

  // 如果需要合并项目
  if (mergeProjects.value) {
    data = mergeProjectRecords(data);
  }

  return data
})

// 计算属性：根据includeNonProjects的值过滤数据
const filteredData = computed(() => {
  if (includeNonProjects.value) {
    return fetchedData.value
  } else {
    return fetchedData.value.filter(item => item.isValidProject !== false)
  }
})

// 计算属性：根据村筛选器过滤数据
const villageFilteredData = computed(() => {
  if (!villageFilter.value) {
    return processedData.value
  }
  return processedData.value.filter(item =>
      item.projectName && item.projectName.includes(villageFilter.value)
  )
})

// 提交按钮是否可用
const canSubmit = computed(() => {
  if (isFetching.value) return false;
  if (!selectedDepartment.value) return false;

  if (searchType.value === 'page') {
    return fetchForm.value.startPage && fetchForm.value.endPage;
  }

  if (searchType.value === 'date') {
    return fetchForm.value.startDate && fetchForm.value.endDate;
  }

  return false;
});

// 表格样式
const headerCellStyle = () => ({
  'background-color': '#f5f7fa',
  height: '43px',
  padding: 0
})

const rowStyle = {height: '77.82px'}

const cellStyle = {
  padding: '2px',
  margin: 0,
  maxHeight: '77.82px',
  overflow: 'hidden'
}

// 日期禁用函数
const disabledDate = (time) => {
  return time.getTime() > Date.now() ||
      time.getTime() < new Date('2018-12-31').getTime();
}

// 计算前一个月日期
const getOneMonthAgo = () => {
  const oneMonthAgo = new Date();
  oneMonthAgo.setMonth(oneMonthAgo.getMonth() - 1);
  return formatDate(oneMonthAgo, 10);
};

// 初始化时间范围
fetchForm.value.startDate = getOneMonthAgo();
fetchForm.value.endDate = formatDate();

// 处理时间范围变化
const handleTimeRangeChange = (val) => {
  selectAllTime.value = false;
  const today = new Date();
  fetchForm.value.endDate = today;

  const startDate = new Date(today);
  switch (val) {
    case 1:
      startDate.setMonth(today.getMonth() - 1);
      break;
    case 2:
      startDate.setMonth(today.getMonth() - 2);
      break;
    case 3:
      startDate.setMonth(today.getMonth() - 3);
      break;
    case 6:
      startDate.setMonth(today.getMonth() - 6);
      break;
    case 12:
      startDate.setFullYear(today.getFullYear() - 1);
      break;
  }

  fetchForm.value.startDate = startDate;
};

// 处理自定义时间选择
const handleSelectAllTimeChange = (val) => {
  if (val) {
    selectedTimeRange.value = null;
    fetchForm.value.startDate = null;
    fetchForm.value.endDate = null;
  } else {
    selectedTimeRange.value = 1;
    handleTimeRangeChange(1);
  }
};

// 处理排序变化
const handleSortByNameChange = () => {
  currentPage.value = 1
  if (!sortByName.value) {
    mergeProjects.value = false
  }
}

// 处理合并项目变化
const handleMergeProjectsChange = () => {
  currentPage.value = 1
}

// 处理包含非工程项目变化
const handleIncludeNonProjectsChange = () => {
  currentPage.value = 1
}

// 处理分页大小变化
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
}

// 处理当前页变化
const handleCurrentChange = (val) => {
  currentPage.value = val
}

// 获取乡镇数据
const fetchDepartments = async () => {
  departmentsLoading.value = true
  try {
    const response = await axios.get(`${baseUrl}/webapi/town/list`)

    if (response.data.success) {
      departments.value = response.data.data
      filteredDepartments.value = response.data.data
    }
  } catch (error) {
    console.error('获取乡镇数据失败:', error)
    ElMessage.error('获取乡镇数据失败')
  } finally {
    departmentsLoading.value = false
  }
}

// 搜索乡镇
const searchDepartments = (query) => {
  if (query) {
    departmentsLoading.value = true
    setTimeout(() => {
      departmentsLoading.value = false
      filteredDepartments.value = departments.value.filter(item =>
          item.name.toLowerCase().includes(query.toLowerCase())
      )
    }, 200)
  } else {
    filteredDepartments.value = departments.value
  }
}

// 填充URL
const fillUrl = (value) => {
  if (value) {
    const selectedTown = departments.value.find(town => town.name === value)
    if (selectedTown && selectedTown.url) {
      fetchForm.value.url = selectedTown.url
    }
  } else {
    fetchForm.value.url = ''
  }
}

// 处理村筛选器变化
const handleVillageFilterChange = () => {
  clearTimeout(villageFilter.value)
  villageFilter.value = setTimeout(() => {
    villageFilter.value = villageFilterInput.value
    currentPage.value = 1
  }, 300)
}

// 关闭窗口
const closeWindow = () => {
  const parentOrigin = process.env.VUE_APP_PARENT_ORIGIN;
  window.parent.postMessage({type: 'close-window'}, parentOrigin);
  window.close();
}

// 处理后缀选择变化
const handleSuffixChange = (values) => {
  if (values.length > 1) {
    selectedSuffixes.value = [values[values.length - 1]]
  }
}

// 处理导入Excel文件
const handleImportExcel = () => {
  const input = document.createElement('input');
  input.type = 'file';
  input.accept = '.xlsx,.xls';

  input.onchange = async (e) => {
    const file = e.target.files[0];
    if (!file) return;

    try {
      const data = await readExcelFile(file);
      // 处理导入的数据并更新表格
      fetchedData.value = processImportedData(data);
      showResultsDialog.value = true;
      ElMessage.success('Excel导入成功');
    } catch (error) {
      console.error('导入Excel失败:', error);
      ElMessage.error('导入Excel失败');
    }
  };

  input.click();
};

// 读取Excel文件内容
const readExcelFile = (file) => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = (e) => {
      try {
        const data = new Uint8Array(e.target.result);
        const workbook = XLSX.read(data, { type: 'array' });
        const firstSheet = workbook.Sheets[workbook.SheetNames[0]];
        const jsonData = XLSX.utils.sheet_to_json(firstSheet);
        resolve(jsonData);
      } catch (error) {
        reject(error);
      }
    };
    reader.onerror = (error) => reject(error);
    reader.readAsArrayBuffer(file);
  });
};

// 处理导入的数据并更新表格
const processImportedData = (data) => {
  return data.map(item => ({
    projectName: item['项目名称'] || '',
    constructionAddress: item['项目地址'] || '',
    constructionContent: item['建设内容'] || '',
    biddingTime: item['发包日期'] || '',
    totalPrice: item['发包金额'] || '',
    winningTime: item['中标日期'] || '',
    bidAmount: item['中标金额'] || '',
    winningBidder: item['中标人'] || '',
    sourceUrl: item['数据源'] || '',
    isValidProject: true
  }));
};

// 导出到Excel
const exportToExcel = (data, filename) => {
  const fieldMapping = {
    projectName: '项目名称',
    constructionContent: '建设内容',
    constructionAddress: '项目地址',
    biddingTime: '发包日期',
    totalPrice: '发包金额',
    winningTime: '中标日期',
    bidAmount: '中标金额',
    winningBidder: '中标人',
    url: '如果你对项目有疑问，请直接点击下面网址查看项目详情。因为编辑器的保护机制，需要两次点击才能激活查看。'
  };

  const columnWidths = {
    '项目名称': 30,
    '建设内容': 30,
    '项目地址': 20,
    '发包日期': 10,
    '发包金额': 10,
    '中标日期': 10,
    '中标金额': 10,
    '中标人': 10
  };

  const amountFields = ['发包金额', '中标金额'];

  const mappedData = data.map(item => {
    const mappedItem = {};
    Object.keys(item).forEach(key => {
      const newKey = fieldMapping[key] || key;
      mappedItem[newKey] = item[key];
    });
    return mappedItem;
  });

  const wb = XLSX.utils.book_new();
  const ws = XLSX.utils.json_to_sheet(mappedData);

  const wscols = Object.keys(columnWidths).map(key => ({
    wch: columnWidths[key]
  }));

  ws['!cols'] = wscols;

  if (ws['!ref']) {
    const range = XLSX.utils.decode_range(ws['!ref']);
    for (let C = range.s.c; C <= range.e.c; ++C) {
      const addr = XLSX.utils.encode_col(C) + "1";
      if (ws[addr]) {
        const columnName = ws[addr].v;
        if (amountFields.includes(columnName)) {
          for (let R = range.s.r + 1; R <= range.e.r; ++R) {
            const cellAddr = XLSX.utils.encode_col(C) + (R + 1);
            if (!ws[cellAddr]) continue;
            if (!ws[cellAddr].s) ws[cellAddr].s = {};
            ws[cellAddr].s.alignment = {horizontal: 'right'};
          }
        }
      }
    }
  }

  XLSX.utils.book_append_sheet(wb, ws, "工程项目");
  XLSX.writeFile(wb, filename);
}

// 导出结果
const exportResults = () => {
  const exportData = villageFilteredData.value.map(item => {
    const {isValidProject, ...rest} = item;
    return rest;
  });

  let fileNamePrefix = `${selectedDepartment.value}`;

  if (villageFilter.value) {
    fileNamePrefix += `${villageFilter.value}`;
  }

  if (includeNonProjects.value) {
    fileNamePrefix += '发布项目';
  } else {
    fileNamePrefix += '村级工程项目';
  }

  if (mergeProjects.value) {
    fileNamePrefix += '（合并）';
  }

  fileNamePrefix += '汇总';

  exportToExcel(exportData, `${fileNamePrefix}.xlsx`);
}

// 打开源网址
const openSourceUrl = (row) => {
  const url = row.url
  if (url) {
    window.open(url, '_blank')
  } else {
    ElMessage.warning('未找到项目详情网址')
  }
}

// 导出到小微权力平台
const exportTo = (row) => {
  currentRowData.value = {
    ...row,
    townName: selectedDepartment.value
  };
  showAutoFillDialog.value = true;
};

// 提交检索请求
const submitFetch = async () => {
  sortByName.value = false;
  mergeProjects.value = false;

  if (!formRef.value) return

  await formRef.value.validate(async (valid) => {
    if (!valid) return

    if (!selectedDepartment.value) {
      ElMessage.error('请选择乡镇')
      return
    }

    if (!fetchForm.value.url) {
      ElMessage.error('请选择乡镇以自动填充网址')
      return
    }

    isFetching.value = true
    progress.value = 0
    progressInfo.value = {processedItems: 0, totalItems: 0}
    showResultsDialog.value = true
    fetchedData.value = []

    try {
      const initResponse = await axios.post(`${baseUrl}/webapi/projectResources/initialize`, {
        startPage: fetchForm.value.startPage,
        endPage: fetchForm.value.endPage
      })

      if (!initResponse.data.success) {
        throw new Error(initResponse.data.message || '初始化任务失败')
      }

      const taskId = initResponse.data.taskId
      startProgressPolling(taskId)
      const currentDelay = getCurrentDelaySettings()

      await axios.post(`${baseUrl}/webapi/projectResources/execute`, {
        taskId: taskId,
        baseUrl: fetchForm.value.url,
        startPage: searchType.value === 'page' ? fetchForm.value.startPage : null,
        endPage: searchType.value === 'page' ? fetchForm.value.endPage : null,
        startDate: searchType.value === 'date' ? fetchForm.value.startDate : null,
        endDate: searchType.value === 'date' ? fetchForm.value.endDate : null,
        townName: selectedDepartment.value,
        keepCounty: keepCounty.value,
        projectType: selectedSuffixes.value[0] || '',
        decimalPlaces: decimalPlaces.value,
        mergeProjects: mergeProjects.value,
        includeNonProjects: includeNonProjects.value,
        searchType: searchType.value,
        pageDelay: currentDelay.pageDelay,
        detailDelay: currentDelay.detailDelay
      })

    } catch (error) {
      stopProgressPolling()
      isFetching.value = false
      console.error('检索项目资源时出错:', error)
      ElMessage.error(error.message || '检索失败，请重试')
    }
  })

  window.parent.postMessage({type: 'iframe-resize', mode: 'fullscreen'}, process.env.VUE_APP_PARENT_ORIGIN);
}

// 返回按钮处理
const handleReturn = () => {
  showResultsDialog.value = false;
  window.parent.postMessage({type: 'iframe-resize', mode: 'normal'}, process.env.VUE_APP_PARENT_ORIGIN);
}

// 开始进度轮询
const startProgressPolling = (taskId) => {
  if (progressInterval.value) {
    clearInterval(progressInterval.value)
  }

  progressInterval.value = setInterval(async () => {
    try {
      const timestamp = new Date().getTime()
      const response = await axios.get(`${baseUrl}/webapi/projectResources/progress?taskId=${taskId}&_t=${timestamp}`, {
        headers: {
          'Cache-Control': 'no-cache',
          'Pragma': 'no-cache'
        }
      })

      if (response.data.success) {
        const progressData = response.data.data

        progressInfo.value = {
          processedItems: progressData.processedItems,
          totalItems: progressData.totalItems
        }

        if (progressData.totalItems > 0) {
          progress.value = Math.floor((progressData.processedItems / progressData.totalItems) * 100)
        } else {
          progress.value = 0
        }

        if (progressData.data && Array.isArray(progressData.data)) {
          fetchedData.value = progressData.data
        }

        if (progressData.status === 'completed') {
          // 清除轮询定时器
          if (progressInterval.value) {
            clearInterval(progressInterval.value)
            progressInterval.value = null
          }

          // 确保进度条走满100%
          progress.value = 100

          // 延迟关闭加载状态，让用户看到100%进度
          setTimeout(() => {
            isFetching.value = false
            ElMessage.success(progressData.message || '数据检索任务已完成')
          }, 300)
        } else if (progressData.status === 'failed') {
          stopProgressPolling()
          isFetching.value = false
          ElMessage.error(progressData.message || '检索失败')
        }
      } else {
        stopProgressPolling()
        isFetching.value = false
        ElMessage.error(response.data.message || '获取进度失败')
      }
    } catch (error) {
      console.error('获取进度时出错:', error)
    }
  }, 300)
}

// 停止进度轮询
const stopProgressPolling = () => {
  if (progressInterval.value) {
    clearInterval(progressInterval.value)
    progressInterval.value = null
  }
  progress.value = 100
}

// 组件挂载时获取乡镇数据
onMounted(() => {
  fetchDepartments()
})

// 当弹窗打开时重置表单和获取数据
watch(() => props.visible, (newVal) => {
  if (newVal) {
    fetchForm.value = {
      url: '',
      startPage: null,
      endPage: null
    }
    selectedDepartment.value = ''
    isFetching.value = false
    keepCounty.value = false
    mergeProjects.value = false
    includeNonProjects.value = true
    fetchDepartments()
  }
})
</script>

<style scoped lang="scss">
label {
  font-size: 14px;
}

.text-center {
  text-align: center;
  line-height: 32px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.project-results-container {
  position: fixed;
  top: 0;
  left: 0;
  padding: 20px;
  width: 100%;
  height: 100%;
  background-color: white;
  z-index: 100;
  overflow: hidden;
}

.results-content {
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.results-header {
  flex-shrink: 0;
}

.results-footer {
  flex-shrink: 0;
  padding: 17px 10px 0 10px;
  background-color: #fff;
}

/* 表格样式 */
:deep(.el-table) {
  border: 1px solid #ebeef5;

  .cell {
    box-sizing: border-box;
    line-height: 18px;
    overflow: hidden;
    overflow-wrap: break-word;
    padding: 0 4px !important;
    text-overflow: ellipsis;
    white-space: normal;
  }
}

/* 分页器样式 */
:deep(.el-pagination) {
  .el-pagination__total,
  .el-pagination__sizes,
  .el-pagination__jump {
    color: #606266;
    font-size: 14px;
  }

  .el-pager {
    li {
      border: 1px solid #dcdfe6;
      margin: 0 2px;
      border-radius: 4px;

      &.active {
        background-color: #409eff;
        border-color: #409eff;
        color: #fff;
      }

      &:hover {
        color: #409eff;
      }
    }
  }

  .el-pagination__jump {
    .el-input__inner {
      border-radius: 4px;
    }
  }

  .btn-prev,
  .btn-next,
  .btn-first,
  .btn-last {
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    margin: 0 2px;

    &:disabled {
      color: #c0c4cc;
      background-color: #fff;
    }
  }
}

.dialog-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.button-group {
  display: flex;
  align-items: center;
}

.performance-control {
  display: flex;
  align-items: center;
  margin-right: 20px;

  .performance-label {
    font-size: 14px;
    color: #606266;
    white-space: nowrap;
    margin-right: 10px;
  }

  .performance-segmented {
    width: 180px;
  }

  :deep(.el-segmented) {
    background-color: #f5f7fa;
    border-radius: 4px;
    padding: 2px;

    .el-segmented__item {
      border-radius: 3px;
      transition: all 0.3s;

      &.is-active {
        background-color: #409eff;
        color: white;
      }
    }
  }
}
</style>

